import os
import streamlit as st
import threading
from dao.email_dao import EmailDao
from dao.field_map_dao import FieldMapDao
from sinotrans.utils import Logger
from typing import Dict, List, Optional, Any, Union

class EmailController:
    # 移除类级别的字段映射缓存，改用session state
    _cache_lock = threading.Lock()
    
    def __init__(self):
        self.email_dao = EmailDao()
        self.field_map_dao = FieldMapDao()
        self._init_logger()
        # 确保字段映射缓存已加载到session state
        self._ensure_field_mappings_loaded()
    
    def _init_logger(self):
        """初始化日志系统"""
        current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        debug_path = os.path.join(current_dir, "logs")
        Logger(debug_path=debug_path)
    
    def _ensure_field_mappings_loaded(self):
        """确保字段映射缓存已加载到session state"""
        # 初始化session state中的字段映射缓存
        if 'field_mapping_cache' not in st.session_state:
            st.session_state.field_mapping_cache = {
                'ai_to_db': {},
                'db_to_ai': {},
                'loaded': False
            }
        
        # 如果缓存未加载，则加载
        if not st.session_state.field_mapping_cache['loaded']:
            try:
                self._load_field_mappings_to_session()
                Logger.debug(f"✅ EmailController: 字段映射缓存已加载到session state - {self.get_cache_status()}")
            except Exception as e:
                Logger.error(f"⚠️ EmailController: 字段映射缓存加载失败: {e}")
    
    def _load_field_mappings_to_session(self):
        """加载字段映射到session state缓存"""
        with self.__class__._cache_lock:
            if st.session_state.field_mapping_cache['loaded']:
                return
            try:
                # 使用现有的field_map_dao获取所有映射
                field_mappings = self.field_map_dao.get_all()
                
                # 清空session state缓存
                st.session_state.field_mapping_cache['ai_to_db'].clear()
                st.session_state.field_mapping_cache['db_to_ai'].clear()
                
                # 构建双向映射缓存
                for row in field_mappings:
                    ai_field = row['ai_field_name']
                    db_field = row['db_field_name']
                    if ai_field and db_field:
                        st.session_state.field_mapping_cache['ai_to_db'][ai_field] = db_field
                        st.session_state.field_mapping_cache['db_to_ai'][db_field] = ai_field
                
                st.session_state.field_mapping_cache['loaded'] = True
                Logger.debug(f"✅ EmailController字段映射缓存加载到session state完成，共 {len(st.session_state.field_mapping_cache['ai_to_db'])} 个映射")
                
            except Exception as e:
                raise RuntimeError(f"❌ EmailController加载字段映射缓存到session state失败: {e}")
    
    def _get_db_field_name_cached(self, ai_field_name: str) -> str:
        """使用session state缓存获取数据库字段名"""
        return st.session_state.field_mapping_cache['ai_to_db'].get(ai_field_name)
    
    def _get_ai_field_name_cached(self, db_field_name: str) -> str:
        """使用session state缓存获取AI字段名"""
        return st.session_state.field_mapping_cache['db_to_ai'].get(db_field_name, db_field_name)
    
    def _convert_ai_to_db_with_cache(self, search_conditions: Dict[str, str]) -> Dict[str, str]:
        """使用session state缓存转换搜索条件的字段名为"%数据库字段名%"""
        conditions = {}
        if search_conditions:
            for ai_field, value in search_conditions.items():
                if value and value.strip():  # 只处理非空值
                    db_field = self._get_db_field_name_cached(ai_field)
                    if db_field:  # 只有找到映射的字段才添加到条件中
                        # 使用LIKE查询支持模糊匹配
                        conditions[db_field] = f'%{value.strip()}%'
        return conditions
    
    def _convert_db_to_ai_with_cache(self, records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """使用session state缓存批量转换记录的字段名为AI识别字段名"""
        converted_records = []
        for record in records:
            converted_record = {}
            for db_field, value in record.items():
                ai_field = self._get_ai_field_name_cached(db_field)
                converted_record[ai_field] = value
            converted_records.append(converted_record)
        return converted_records
    
    @classmethod
    def get_cache_status(cls):
        """获取session state缓存状态"""
        if 'field_mapping_cache' not in st.session_state:
            return {
                'loaded': False,
                'ai_to_db_count': 0,
                'db_to_ai_count': 0
            }
        return {
            'loaded': st.session_state.field_mapping_cache['loaded'],
            'ai_to_db_count': len(st.session_state.field_mapping_cache['ai_to_db']),
            'db_to_ai_count': len(st.session_state.field_mapping_cache['db_to_ai'])
        }
    
    @classmethod
    def clear_cache(cls):
        """清空session state缓存（仅在需要强制重新加载时使用）"""
        if 'field_mapping_cache' in st.session_state:
            st.session_state.field_mapping_cache['ai_to_db'].clear()
            st.session_state.field_mapping_cache['db_to_ai'].clear()
            st.session_state.field_mapping_cache['loaded'] = False
            Logger.debug("🔄 EmailController字段映射缓存已从session state清空")

    @st.cache_data(ttl=300)  # 缓存5分钟
    def query_emails_with_pagination_cached(_self, page: int = 1, page_size: int = 20, 
                                search_conditions: Dict[str, str] = None) -> Dict[str, Any]:
        """带缓存的分页查询邮件数据"""
        return _self.query_emails_with_pagination(page, page_size, search_conditions)
        
    def query_emails_with_pagination(self, page: int = 1, page_size: int = 20, 
                               search_conditions: Dict[str, str] = None) -> Dict[str, Any]:
        """分页查询邮件数据（使用session state缓存优化）"""
        try:        
            # 使用session state缓存转换搜索条件
            conditions = self._convert_ai_to_db_with_cache(search_conditions)
        
            # 计算偏移量
            offset = (page - 1) * page_size
            
            # 查询数据
            email_data = self.email_dao.query(
                conditions=conditions,
                order_by='id ASC',  # 改为按ID升序，提高分页性能
                limit=page_size,
                offset=offset
            )
            
            # 统计总数
            total_count = self.email_dao.count_records(conditions=conditions)
            
            # 计算分页信息
            total_pages = (total_count + page_size - 1) // page_size
            
            # 使用session state缓存批量转换字段名（修复：db字段转ai字段）
            converted_data = self._convert_db_to_ai_with_cache(email_data)
            
            return {
                'data': converted_data,
                'total_count': total_count,
                'total_pages': total_pages,
                'current_page': page,
                'page_size': page_size,
                'has_next': page < total_pages,
                'has_prev': page > 1
            }
            
        except Exception as e:
            st.error(f"查询邮件数据失败: {str(e)}")
            return {
                'data': [],
                'total_count': 0,
                'total_pages': 0,
                'current_page': page,
                'page_size': page_size,
                'has_next': False,
                'has_prev': False
            }
    
    def get_email_detail_by_uid(self, uid: str) -> Dict[str, Any]:
        """根据UID获取邮件详情（使用session state缓存优化）"""
        try:
            # 查询单条记录
            results = self.email_dao.query(conditions={'uid': uid}, limit=1)
            
            if results:
                # 使用session state缓存转换字段名
                converted_records = self._convert_db_to_ai_with_cache(results)
                return converted_records[0] if converted_records else {}
            else:
                return {}
                
        except Exception as e:
            st.error(f"获取邮件详情失败: {str(e)}")
            return {}
